﻿Imports System.Xml
Imports System.Text
Imports My.InfoPathDecoder


Public Class FileInfoGrabber
    Public Function ParseXmlFiles(ByVal oXml As XmlDocument, ByVal oNS As XmlNamespaceManager, ByVal anyXPath As String) As DataTable
        Dim xmlFileNodeList As XmlNodeList = oXml.SelectNodes(anyXPath, oNS)
        Dim filesExists As Boolean = False
        For Each eachFileNode As XmlNode In xmlFileNodeList
            'Dim eachFile As String = eachFileNode("my:v2_submit_to_dropdown").InnerText
            If (Not String.IsNullOrEmpty(eachFileNode.InnerText)) Then
                'MessageBox.Show(eachFileNode.InnerText)
                'Dim dt As New DataTable()
                'dt.Columns.Add(New DataColumn("OriginalfileName",TypeOf(String))
                'dt.Columns.Add(New DataColumn("OriginalfileName",String)
                Dim ofn As String = eachFileNode.Name
                SaveFile(eachFileNode.InnerText, eachFileNode.Name, ofn)
                filesExists = True
            End If
        Next

        If Not (filesExists) Then
            'MessageBox.Show("File attachmennot found for this item")
        End If

        Return Table1
    End Function
    Private Sub SaveFile(ByVal data As String, ByVal fileNodeName As String, ByRef ofn As String)
        Try
            Dim binaryData As Byte() = Convert.FromBase64String(data)

            'Position 20 contains DWORD indicating the length of the filename buffer.
            'The filename is stored as Unicode so the lenth is multiplied by 2

            Dim fnLength As Integer = binaryData(20) * 2
            Dim b As Byte()
            ReDim b(fnLength)

            Dim fnBytes As Byte() = b

            ' Actual Filename starts at position 24
            'For (Dim i As integer = 0 To 
            For i As Integer = 0 To fnBytes.Length - 1
                fnBytes(i) = binaryData(24 + i)
            Next

            Dim chars As Char() = UnicodeEncoding.Unicode.GetChars(fnBytes)
            Dim fileName As String = New String(chars)
            fileName = fileName.Substring(0, fileName.Length - 2)
            'ofn += fileName
            'Write out the decoded data
            Dim filePath As String = "c:\\temp\\"
            If (ValiadateFileName(fileName)) Then
                fileName = filePath + fileName
                Dim outFile As System.IO.FileStream = New System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)

                Dim ipaDecoder As InfoPathAttachmentDecoder = New InfoPathAttachmentDecoder(binaryData)


                Dim numRef As Byte()
                numRef = ipaDecoder.DecodedFile()

                outFile.Write(numRef, 0, numRef.Length)

                CreateTable(PrepareDataTable(), fileName, fileNodeName, filePath, "Successfully saved")
                outFile.Close()
            End If

        Catch ex As Exception
            Console.WriteLine("Error:" + ex.Message)
        End Try
    End Sub

    Function ValiadateFileName(ByVal proposedFilename As String) As Boolean
        Dim isValid As Boolean = True

        Try
            Dim invalidCharBag As Char() = System.IO.Path.GetInvalidFileNameChars()
            Dim c As Char
            Dim i As Integer = 0
            For Each c In invalidCharBag
                If (proposedFilename.Contains(c)) Then
                    isValid = False
                    Exit For
                End If
            Next
            Return isValid
        Catch ex As Exception
            Return isValid
        End Try
    End Function
    Function ValiadateFilePath(ByVal proposedFilepath As String) As Boolean
        Dim isValid As Boolean = True
        Try
            Dim invalidCharBag As Char() = System.IO.Path.GetInvalidPathChars()
            Dim c As Char
            Dim i As Integer = 0
            For Each c In invalidCharBag
                If (proposedFilepath.Contains(c)) Then
                    isValid = False
                    Exit For
                End If
            Next
          
            Return isValid
        Catch ex As Exception
            Return isValid
        End Try
    End Function

    Dim Table1 As DataTable = Nothing

    Private Function PrepareDataTable() As DataTable
        If (IsNothing(Table1)) Then
            Table1 = New DataTable("Attachments")
            Dim Name As DataColumn = New DataColumn("FileName")
            'declaring a column named Name
            Name.DataType = System.Type.GetType("System.String")
            'setting the datatype for the column
            Table1.Columns.Add(Name)
            'adding the column to table
            Dim Product As DataColumn = New DataColumn("Original")
            Product.DataType = System.Type.GetType("System.String")
            Table1.Columns.Add(Product)
            Dim Location As DataColumn = New DataColumn("Path")
            Location.DataType = System.Type.GetType("System.String")
            Table1.Columns.Add(Location)

            Dim Statuts As DataColumn = New DataColumn("Status")
            Statuts.DataType = System.Type.GetType("System.String")
            Table1.Columns.Add(Statuts)
        End If

        'creating a table named Attachments
        Return Table1
    End Function

    Private Sub CreateTable(ByVal Table1 As DataTable, ByVal newFileName As String, ByVal oldFileName As String, ByVal path As String, ByVal Status As String)

        Dim Row1 As DataRow
        'declaring three rows for the table
        Try
            Row1 = Table1.NewRow()
            'declaring a new row
            Row1.Item("FileName") = newFileName
            'filling the row with values. Item property is used to set the field value.
            Row1.Item("Original") = oldFileName
            'filling the row with values. adding a product
            Row1.Item("Path") = path
            'filling the row with values. adding a location
            Row1.Item("Status") = Status
            'filling the row with values. adding a location
            Table1.Rows.Add(Row1)
            'adding the completed row to the table

        Catch ex As Exception
        End Try
    End Sub
End Class
